from LeavingMsg import app, db
from flask import render_template, url_for, redirect, flash, request
from LeavingMsg.models import Messages
from LeavingMsg.forms import MsgBoard
from datetime import datetime


@app.route('/', methods=['GET', 'POST'])
def index():
    count = Messages.query.count()
    if count == 0:
        welcome = Messages(name='Admin', body='Welcome to my leaving board~!', timestamp=datetime.utcnow())
        db.session.add(welcome)
        db.session.commit()
    form = MsgBoard()
    if form.validate_on_submit():
        name = form.name.data
        body = form.body.data
        messages = Messages(name=name, body=body)
        db.session.add(messages)
        db.session.commit()
        flash('留言提交成功')
        return redirect(url_for('index'))
    # 对消息进行分页
    page = request.args.get('page', 1, type=int)
    # 对查询结果进行降序，按照时间由近及远展示
    msgs = Messages.query.order_by(Messages.timestamp.desc()).paginate(page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('index', page=msgs.next_num) if msgs.has_next else None  # 下一页
    prev_url = url_for('index', page=msgs.prev_num) if msgs.has_prev else None  # 上一页
    return render_template('index.html', form=form, messages=msgs.items, next_url=next_url, prev_url=prev_url,
                           msgs=msgs.items, count=count)


@app.shell_context_processor
def make_shell_context():
    return dict(db=db, Messages=Messages)
